use chrono::Local;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::Path;

pub struct AccountLogger {
    log_dir: String,
}

impl AccountLogger {
    pub fn new() -> Self {
        let log_dir = "logs".to_string();
        
        // 创建logs目录
        if let Err(e) = fs::create_dir_all(&log_dir) {
            eprintln!("Failed to create log directory: {}", e);
        }
        
        Self { log_dir }
    }

    /// 为账号记录日志 (分层结构: logs/任务名/账号.log)
    pub fn log(&self, account_key: &str, level: &str, message: &str) {
        // account_key格式: "task_name:nickname"
        let parts: Vec<&str> = account_key.split(':').collect();
        if parts.len() != 2 {
            return;
        }
        
        let task_name = parts[0];
        let nickname = parts[1];
        
        // 创建任务子目录
        let task_log_dir = format!("{}/{}", self.log_dir, task_name);
        if let Err(e) = fs::create_dir_all(&task_log_dir) {
            eprintln!("Failed to create task log directory: {}", e);
            return;
        }
        
        // 安全的文件名
        let safe_nickname = nickname.replace(['/', '\\', ':', '*', '?', '"', '<', '>', '|', '@'], "_");
        let log_file = format!("{}/{}.log", task_log_dir, safe_nickname);
        
        let timestamp = Local::now().format("%Y-%m-%d %H:%M:%S");
        let log_entry = format!("[{}] [{}] {}\n", timestamp, level, message);
        
        // 追加写入日志文件
        if let Ok(mut file) = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&log_file)
        {
            let _ = file.write_all(log_entry.as_bytes());
        }
    }

    /// 记录INFO级别日志
    pub fn info(&self, account_key: &str, message: &str) {
        self.log(account_key, "INFO", message);
    }

    /// 记录WARN级别日志
    pub fn warn(&self, account_key: &str, message: &str) {
        self.log(account_key, "WARN", message);
    }

    /// 记录ERROR级别日志
    pub fn error(&self, account_key: &str, message: &str) {
        self.log(account_key, "ERROR", message);
    }

    /// 清理旧日志(可选功能)
    #[allow(dead_code)]
    pub fn cleanup_old_logs(&self, days: u32) -> Result<(), String> {
        let log_dir = Path::new(&self.log_dir);
        if !log_dir.exists() {
            return Ok(());
        }

        let now = Local::now();
        let entries = fs::read_dir(log_dir)
            .map_err(|e| format!("Failed to read log directory: {}", e))?;

        for entry in entries.flatten() {
            if let Ok(metadata) = entry.metadata() {
                if let Ok(modified) = metadata.modified() {
                    let modified_time = chrono::DateTime::<Local>::from(modified);
                    let age = now.signed_duration_since(modified_time);
                    
                    if age.num_days() > days as i64 {
                        let _ = fs::remove_file(entry.path());
                    }
                }
            }
        }

        Ok(())
    }
}
